/* 
 * File:   DescriptorReader.cpp
 * Author: max
 * 
 * Created on April 3, 2013, 11:41 PM
 */

#include <sstream>
#include "Descriptor.h"
#include "Mangle.h"

using namespace TP3::Mangling;

Descriptor::Descriptor(char delimiter) {
    _delimiter = delimiter;
}

Descriptor::~Descriptor() {
}

string& Descriptor::getName(){
    
    return _ruleName;
    
}

string* Descriptor::getParameters(){
    return _params;
}

int Descriptor::getCntParameters(){
    return _cntParams;
}

void Descriptor::reset(){
    
    _ruleName = "";
    _cntParams = 0;
    for (int x = 0; x < MAX_CNT_PARAMS; x ++)
    {
        _params[x]="";
    }
}

string& Descriptor::toString (){
    
    _representation = this->getName();
    
    for (int x = 0; x < this->getCntParameters(); x++)
    {
        if (_representation.length() > 0)
            _representation += " ";
        
        _representation += this->getParameters()[x];
    }  
    
    return _representation;
}

    
    void Descriptor::readDescriptorData (string& descriptor, istream& input, const char delimiter){
        
        descriptor = "";
        char aux;
        string aux2;
        bool terminar = false;
       
        while (!input.eof() && !terminar){
            
            input >> std::noskipws >> aux;
            
            if (aux != '\n' && aux != '\r'){
                
                terminar = ( delimiter == (char) aux );

                if (!terminar)
                    descriptor += (char) aux;
            }
        }
    }
    
        
    void Descriptor::parseDescriptorData (Descriptor& descriptor, const string& descriptorData){
        
        if (descriptorData.length() > 0)
        {
            std::stringstream reader;
            reader.str (descriptorData);

            // Populo el descriptor.

            reader >> descriptor._ruleName;

            string token = "";
            int parametersCounter = 0;

            while (! reader.eof() && parametersCounter < MAX_CNT_PARAMS)
            {
                reader >> token;
                descriptor._params[parametersCounter++] = token;
            }

            descriptor._cntParams = parametersCounter;
        }

    }    

namespace TP3 { namespace Mangling {
    
    istream& operator>> (istream& input, Descriptor& descriptor){
        
        // Extraigo del stream el descriptor.

        string descriptorData;
        descriptor.readDescriptorData (descriptorData, input, descriptor._delimiter);
        
        // Inicializao el descriptor.

        descriptor.reset();

        descriptor.parseDescriptorData (descriptor, descriptorData);
        
        return input;
    }
}}

